<template>
  <view class="record-wrapper">
    <!-- 使用 catch:touchmove 防止事件冒泡 -->
    <view
      class="record-item"
      :id="'itemRef-' + record.id"
      :class="{ swiped: isSwiped }"
      @touchstart="onTouchStart"
      @touchmove.stop="onTouchMove"
      @touchend="onTouchEnd"
      @tap="onItemClick"
      :style="style"
      ref="itemRef"
    >
      <view class="record-info">
        <view class="record-main">
          <text class="record-category">{{ record.category }}</text>
          <text
            class="record-amount"
            :class="{ income: record.expenseType === '2', expense: record.expenseType === '1' }"
          >
            {{ record.expenseType === '2' ? '+' : '-' }}{{ record.amount }}元
          </text>
        </view>
        <view class="record-detail">
          <text class="record-time">{{ record.expenseTime }}</text>
          <text class="record-payment">{{ record.paymentMethod }}</text>
        </view>
        <text class="record-remark" v-if="record.remark">{{ record.remark }}</text>
      </view>
    </view>
    <view class="record-action" @tap.stop="onDelete" :style="btnStyle">
      <text class="delete-btn">删除</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { FinanceRecord } from '@/types/finance'

const props = defineProps<{ record: FinanceRecord }>()
const emit = defineEmits<{ click: [record: FinanceRecord]; delete: [id: string] }>()

// 引用当前组件元素
const itemRef = ref<any>(null)

// 滑动相关状态
const isSwiped = ref(false)
const startX = ref(0)
const moveX = ref(0)
const currentX = ref(0)
const style = ref<any>({
  transform: 'translateX(0)',
  transition: 'none',
  '-webkit-transform': 'translateX(0)',
})
const btnStyle = ref<any>({
  transform: 'translateX(0)',
})
// 触摸开始 - 完全适配微信小程序
const onTouchStart = (e: any) => {
  try {
    // 微信小程序触摸事件对象结构
    const touch = e.touches && e.touches[0] ? e.touches[0] : e.changedTouches[0]
    if (touch) {
      // 微信小程序使用 pageX/pageY
      startX.value = touch.pageX
    }
    currentX.value = isSwiped.value ? 200 : 0 // 使用rpx对应的值
  } catch (error) {
    console.error('onTouchStart error:', error)
  }
}

// 触摸移动 - 完全适配微信小程序
const onTouchMove = (e: any) => {
  try {
    const touch = e.touches[0]
    if (!touch) return
    // 使用rpx单位计算位移
    const windowInfo = uni.getWindowInfo()
    const deltaX = (touch.pageX - startX.value) * (750 / windowInfo.windowWidth)
    let newX = Math.max(Math.min(deltaX, 200), 0)
    const transformValue = `translateX(${newX}rpx)`
    style.value.transform = transformValue
    style.value['-webkit-transform'] = transformValue
    style.value.transition = 'none'
    // 保存当前移动位置，用于touchend判断
    moveX.value = touch.pageX
  } catch (error) {
    console.error('滑动处理异常:', error)
  }
}

// 触摸结束 - 修复单位混用问题
const onTouchEnd = (e: any) => {
  try {
    // 获取触摸结束时的X坐标
    const touch = e.changedTouches && e.changedTouches[0] ? e.changedTouches[0] : null
    if (touch) {
      moveX.value = touch.pageX
    }

    const diffX = (moveX.value - startX.value) * (750 / uni.getSystemInfoSync().windowWidth)
    console.log('diffX', diffX)
    // 判断阈值调整为rpx单位
    if (diffX > 60) {
      // 对应120rpx，向左滑动
      isSwiped.value = true

      style.value.transform = 'translateX(200rpx)'
      style.value.duration = 300
      style.value.fill = 'forwards'
      btnStyle.value.transform = 'translateX(0)'
    } else {
      // 恢复原位
      isSwiped.value = false
      style.value.transform = 'translateX(0)'
      style.value.duration = 300
      style.value.fill = 'forwards'
      btnStyle.value.transform = 'translateX(-200rpx)'
    }
  } catch (error) {
    console.error('onTouchEnd error:', error)
  }
}
// 点击记录
const onItemClick = () => {
  // 如果当前是滑动状态，先恢复原位
  // 统一设置过渡动画属性，确保平滑恢复
  style.value.transform = 'translateX(0)'
  style.value['-webkit-transform'] = 'translateX(0)'

  // 同步恢复删除按钮的位置
  btnStyle.value.transition = 'transform 0.3s ease'
  btnStyle.value.transform = 'translateX(-200rpx)'

  isSwiped.value = false
}

// 删除记录
const onDelete = () => {
  emit('delete', props.record.id!)
  // 删除后重置滑动状态
  isSwiped.value = false
  style.value.transform = 'translateX(0)'
  style.value.webkitTransform = 'translateX(0)'
}
</script>

<style lang="scss">
.record-wrapper {
  position: relative;
  overflow: hidden;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  height: 180rpx; // 设置固定高度，确保滑动效果
}

.record-item {
  transform: translateX(0);
  /* 添加以下属性优化移动性能 */
  backface-visibility: hidden;
  perspective: 1000px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  position: absolute; // 使用绝对定位
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  // 关键优化：添加will-change提升性能
  will-change: transform;
  // 确保z-index正确
  z-index: 2;
  // 兼容微信小程序的过渡动画
  transition: transform 0.3s ease;
  -webkit-transition: -webkit-transform 0.3s ease;

  .record-info {
    flex: 1;
    .record-main {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10rpx;
      .record-category {
        font-size: 32rpx;
        color: #333;
      }
      .record-amount {
        font-size: 36rpx;
        font-weight: bold;
        &.income {
          color: #409eff;
        }
        &.expense {
          color: #f56c6c;
        }
      }
    }
    .record-detail {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8rpx;
      .record-time {
        font-size: 24rpx;
        color: #999;
      }
      .record-payment {
        font-size: 24rpx;
        color: #666;
      }
    }
    .record-remark {
      font-size: 24rpx;
      color: #999;
      display: block;
    }
  }
}

.record-action {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 200rpx;
  background-color: #f56c6c;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
  transform: translateX(-200rpx); /* 初始隐藏位置 */
  .delete-btn {
    color: #fff;
    font-size: 28rpx;
  }
}

/* 响应式适配 */
@media screen and (max-width: 320px) {
  .record-main {
    flex-direction: column;
    align-items: flex-start !important;
  }
  .record-amount {
    margin-top: 5rpx;
  }
  .record-detail {
    flex-direction: column;
    align-items: flex-start !important;
  }
  .record-payment {
    margin-top: 5rpx;
  }
}
</style>
